package user

import (
	"context"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/user"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzusersurvey"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserSurveyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUserSurveyListLogic - 用户问卷列表
func NewUserSurveyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSurveyListLogic {
	return &UserSurveyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserSurveyListLogic) UserSurveyList(req *types.UserSurveyRequest) (resp *types.UserSurveyResponse, err error) {
	// 创建实例
	userSurveyDao := user.NewUserSurveyDao(l.ctx, l.svcCtx)

	// 查询用户问卷信息
	userSurveyConditions := make([]predicate.HzUserSurvey, 0)
	userSurveyConditions = append(userSurveyConditions, hzusersurvey.DeleteAtIsNil())
	userSurveyConditions = append(userSurveyConditions, hzusersurvey.UserSurveyTypeEQ(req.UserSurveyType))
	userSurveyList, verCount, err := userSurveyDao.UserSurveyConditionsAllByPage(userSurveyConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, err
	}

	// 组装数据
	list := lo.Map(userSurveyList, func(item *ent.HzUserSurvey, _ int) *types.UserSurveyInfo {
		return &types.UserSurveyInfo{
			Id:                 int64(item.ID),
			UserSurveyPhone:    item.UserSurveyPhone,
			UserSurveyName:     item.UserSurveyName,
			UserSurveySex:      item.UserSurveySex,
			UserSurveyOrderNum: item.UserSurveyOrderNum,
			CreatedAt:          time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			UpdateAt:           time.Unix(item.UpdateAt, 0).Format(time.DateTime),
		}
	})

	// 返回数据
	resp = &types.UserSurveyResponse{
		Page: types.PageResponse{
			Total:           verCount,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}

	return resp, nil
}
